package binance.controller
import binance.model.*

class BuyController {

    def register = {
        [stockmarkets : Stockmarket.list(sort:"name")]
    }

    def search_register = {
        def stock = Stock.findById(params['stock'])
        if (stock) {
            return [stock : stock]
        }
    }

    def stocklist = {
        def stockmarket = Stockmarket.findById(params['stockmarket'])
        if (stockmarket) {
            def stocklists = Stocklist.findAllByStockmarket(stockmarket,[sort:'code'])
            return [stocklists : stocklists]
        }
        
        render(text:"Select a stock market")
    }

    def stock = {        
        try {
            def stocklist = Stocklist.findById(params['stocklist'])
            if (stocklist) {
                return [stocks : Stock.findAllByStocklist(stocklist,[sort:'name'])]
            }
        } catch (Exception e) { }

        render(text:"Select a stock list")
    }

    def details = {
        try {
            def stock = Stock.findById(params['stock'])
            if (stock) {
                return [stock : stock]
            }
        } catch (Exception e) { }
        render(text:"Select a stock")
    }

    def edit = {
        def buy = Buy.findByIdAndUser(params['id'],session.user)
        return [buy : buy]
    }

    def save = {
        params['price'] = Utils.correctNumber(params['price'])
        params['count'] = Utils.correctNumber(params['count'])
        params['target'] = Utils.correctNumber(params['target'])
        def user = session.user
        def stock = Stock.findById(params['stock'])
        def buy = new Buy(user:user,stock:stock,price:params['price'],count:params['count'],target:params['target'])

        if (buy.save())
            render(text:"Successfully registered $buy")
        else
            render(text:"Error while registering $buy")
    }

    def update = {
        params['price'] = Utils.correctNumber(params['price'])
        params['count'] = Utils.correctNumber(params['count'])
        params['target'] = Utils.correctNumber(params['target'])
        def buy = Buy.findByIdAndUser(params['id'],session.user)
        buy.count = Integer.parseInt(params['count'])
        buy.price = new Double(params['price'])
        buy.target = new Double(params['target'])
        buy.save()
        redirect(controller:"page",action:"start")
    }

    def delete = {
        def buy = Buy.findByIdAndUser(params['id'],session.user)
        if (buy.stocksSold() > 0) {
            buy.count = buy.stocksSold()
            buy.save()
        } else {
            buy.delete()
        }
        redirect(controller:"page",action:"start")
    }
}
